import config from './config.js';
import store from '../store'

const getData = (api, param = {}, method = 'GET') => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: api,
			data: param,
			header: {},
			method,
			dataType: "json",
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showModal({
					title:"网络超时，请检查网络连接",
				})
				console.log(err)
				reject(err)
			}
		});
	});
}

const Http = (api, param = {}, method = 'GET') => {
	
	let token = uni.getStorageSync('token');
	return new Promise((resolve, reject) => {
		if(!store.state.networkStatus){
			uni.hideLoading();
			uni.showToast({
				title:"当前网络状态不可用，请检查网络连接",
				icon:"none"
			})
			reject({})
			return false;
		}
		uni.request({
			url: config.host + api,
			data: param,
			header: {
				token
			},
			method,
			dataType: "json",
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showModal({
					title:"网络超时，请检查网络连接",
				})
				console.log(err)
				reject(err)
			}
		});
	});
}

const Upload = (api, filePath = [], param = {}, hostMode = 0) => {
	let token = uni.getStorageSync('token'),
		hostArray = [config.host, 'https://'],
		keyNameArray = ["file", 'upload'],
		url = hostArray[hostMode] + api;
	console.log(url);
	return new Promise((resolve, reject) => {
		if(!store.state.networkStatus){
			uni.hideLoading();
			uni.showToast({
				title:"当前网络状态不可用，请检查网络连接",
				icon:"none"
			})
			reject({})
			return false;
		}
		uni.uploadFile({
			url,
			filePath,
			name: keyNameArray[hostMode],
			formData: param,
			header: {
				token
			},
			success: (uploadFileRes) => {
				resolve(uploadFileRes);
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showModal({
					title:"网络超时，请检查网络连接",
				})
				console.log(err)
				reject(err)
			}
		});
	});
}




export default {
	Http,
	getData,
	Upload
}
